from email.utils import formatdate, make_msgid

import mcp.server.fastmcp as fastmcp
import requests
import smtplib
from email.mime.text import MIMEText
from email.header import Header

mcp = fastmcp.FastMCP("Weather MCP Server")

@mcp.resource(
    uri="file:///weather_code.txt",
    name="weather_code",
    description="根据城市的名称查询对应的地区编码 adcode和城市编码 citycode",
    mime_type="text/plain",
)
def weather_code()->str:
    """
    返回所有的城市的名称，地区编码 adcode,城市编码 citycode
    :return: 名称，地区编码 adcode,城市编码 citycode
    """
    with open("weather_code.data", "r",encoding="utf-8") as file:
        content = file.read()
    #返回查询的内容
    return content

@mcp.tool()
def query_weather(adcode: str)->str:
    """
    根据城市的地区编号查询对应的天气信息
    :param adcode: 地区编号
    :return: 天气信息
    """
    url = f"https://restapi.amap.com/v3/weather/weatherInfo?key=d64c259dde4173ce7be767be32eb2bb9&city={adcode}&extensions=all"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        # 处理返回的数据
        print("查询API接口返回的数据：",data)
        return data
    else:
        print("查询API接口失败")
        return "查询API接口失败"

@mcp.tool()
def send_email(to:str, subject:str, content:str)->str:
    """
    发送电子邮件
    :param to: 收件人邮箱地址
    :param subject: 邮件主题
    :param content: 邮件内容
    :return: 发送结果
    """
    # 发件人邮箱配置
    sender = '15816469091@163.com'
    password = 'GEfMHKhcs2jLW3RK'
    smtp_server = 'smtp.163.com'
    smtp_port = 465

    try:
        # 创建邮件对象
        message = MIMEText(content, 'plain', 'utf-8')
        # 严格按照RFC5322格式设置From头
        message['From'] = f'<{sender}>'  # 使用英文双引号包裹显示名称
        message['To'] = f'<{to}>'  # 收件人也用尖括号包裹
        message['Subject'] = Header(subject, 'utf-8')
        # 添加必要的邮件头
        message['Date'] = formatdate(localtime=True)
        message['Message-ID'] = make_msgid()

        # 连接SMTP服务器并发送邮件
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
            server.login(sender, password)
            server.sendmail(sender, [to], message.as_string())

        print(f"邮件已成功发送到 {to}")
        return f"邮件已成功发送到 {to}"
    except Exception as e:
        error_msg = f"发送邮件时出错: {str(e)}"
        print(error_msg)
        return error_msg


if __name__ == "__main__":
    print(" MCP Server Start!")
    mcp.run(transport="sse")


